from statistics import mode
import torch
import torch.nn as nn
from thop import profile



class CNNFIVE(nn.Module):
    def __init__(self, num_classes, init_weights=True):
        super().__init__()
        self.features = nn.Sequential(
            # Block 1
            nn.Conv2d(3, 64, 3, stride = 1, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(64, 128, 3, stride = 2, padding=1),
            nn.ReLU(inplace=True),
            # nn.MaxPool2d(2, stride=2),
            # Block 2
            nn.Conv2d(128, 256, 3, stride = 1,padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(256, 512, 3, stride = 2,padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(512, 256, 3, stride = 2,padding=1),
            nn.ReLU(inplace=True),
        )
        # self.avgpool = nn.AdaptiveAvgPool2d((7, 7))
        self.classifier = nn.Sequential(
            nn.Linear(256*15*15, 1024),
            nn.ReLU(inplace=True),
            nn.Dropout(),
            #nn.Linear(1024, 1024),
            #nn.ReLU(inplace=True),
            #nn.Dropout(),
        )
        # 因为前面可以用预训练模型参数，所以单独把最后一层提取出来
        self.classifier2 = nn.Linear(1024, num_classes)
        if init_weights:
            self._initialize_weights()

    def forward(self, x):
        x = self.features(x)
        #print(x.shape)
        # x = self.avgpool(x)
        # print(x.shape)
        # torch.flatten 推平操作
        x = torch.flatten(x, 1)
        #print("fuck=", x.shape)
        x = self.classifier(x)
        #print("fuck2=", x.shape)
        x = self.classifier2(x)
        return x

    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                nn.init.normal_(m.weight, 0, 0.01)
                nn.init.constant_(m.bias, 0)
# 查看模型结构
# model = VGG19(num_classes=2, init_weights=True)
# print(model)

#if __name__ == "__main__":
  #  x = torch.ones(8, 3, 128, 128)
  #  model = CNNFIVE(num_classes=2, init_weights=True)
  #  print(model)
   # output =  model(x)
    #print(output.shape)
    #flops, params = profile(model, inputs=(x, ))
    #print('flops:', flops/100000000)
    #print('params:', params/1000000)